<?php

function get_html_tags($text, $tagname, $closetag=true, $close_optional=false) 
{ 
        /* escape PCRE characters in tag name */ 
        $tagname = preg_quote($tagname); 
         
        $ret = array(); 

        /* regular expression to match mattributes in a tag name */ 
        //$attrib_match = "/((?i)[a-z]+) (\s*=\s* ( ((?U)(\"(.*)\")) |(\S+) ) |\s+) /sXi"; 
		$attrib_match = "/((?i)[a-z]+)(\s*=\s*(((?U)(\"(.*)\"))|(\s+))|\s+)/si";
         
        if ($closetag) { 
            if ($close_optional !== false) { 
                $close_optional = preg_quote($close_optional); 
                $regex = "/<$tagname(.*)>(.*)(<\/$tagname>|(?=<$tagname>)|(?=<\/$close_optional>))/Uis"; 
            } else { 
                $regex = "/<$tagname(.*)>(.*)<\/$tagname>/Uis"; 
            } 
        } else { 
            $regex = "/<$tagname((.+))\/?>/Uis"; 
        } 
         
        // regex now matches the tag appropriatly 
         
        preg_match_all($regex, $text, $tags, PREG_SET_ORDER); 

        $tag_count = count($tags); 
         
        for($t = 0; $t < $tag_count; $t++) { 
            $tag = array(); 
             //$tags[$t][1] = str_replace("'",'"', $tags[$t][1]);
			 
            /* get attributes */ 
            preg_match_all($attrib_match, $tags[$t][1], $attributes, PREG_SET_ORDER); 

            $attribs = array(); 

            $attrib_count = count($attributes); 
            for($a = 0; $a < $attrib_count; $a++) {     
                $name = strtolower(trim($attributes[$a][1])); 

                if (isset($attributes[$a][4])) { // name value pair found 
                    $value = trim(isset($attributes[$a][7])?$attributes[$a][7]:$attributes[$a][6]); 
                } else { 
                    $value = $name; 
                } 

                $attribs[$name] = $value;                 
            } 
            if (empty($attribs['href']) && $tagname == 'a') {
				$tags[$t][1] = str_replace(array("\n","\t"),array(""," "), $tags[$t][1]);
				preg_match("/href\s*=\s*\'(.*)\'\s+/", $tags[$t][1], $second_chance);
				$attribs['href'] = @$second_chance[1];
			}
            $tag['attributes'] = $attribs; 
             
            if ($closetag) { 
                $tag['text'] = $tags[$t][2]; 
            } 

            $ret[] = $tag; 
        } 

        return $ret; 
}


?>